var WalleCateModel = require('../models/walleModel')


var walleCateCtrl = {};

//
walleCateCtrl.get = function (req, res) {


    // var skey = req.query.skey;
    // var page = req.query.page || 1;
    var queryCondition = {};

    // if (skey) {
    //     queryCondition.skey = {
    //         $regex: new RegExp(skey, "i")
    //     };
    // }

    WalleCateModel.find(queryCondition).sort({
        // 'stype': 1,
        'ctime': -1
    }).exec(function (err, docs) {
        if (err) {

            res.status(500).json({
                code: -1,
                msg: '没有对应的信息'
            })
        } else {

            res.json({
                code: 0,
                dat: docs
            })
        }
    });




};

//
walleCateCtrl.getOne = function (req, res) {

    var _id = req.query._id;
    WalleCateModel.findOne({ _id: _id }, function (err, item) {

        if (err) {

            res.status(500).json({
                code: -1,
                msg: '没有对应的信息'
            })
        } else {

            res.json({
                code: 0,
                dat: item
            })
        }

    });

};


//
walleCateCtrl.add = function (req, res, next) {

    var data = req.body
    WalleCateModel.create(data, function (err, item) {

        if (err) {

            console.log(err)
            res.status(500).json({
                code: -1,
                msg: '保存数据错误'
            })
        } else {
            res.json({
                code: 0,
                dat: item
            })
        }

    });

}

//
walleCateCtrl.update = function (req, res, next) {

    var data = req.body
    var id = data.id

    WalleCateModel.findOneAndUpdate({ id: id }, data, function (err, item) {

        if (err) {

            console.log(err)

            res.status(500).json({
                code: -1,
                msg: '保存数据错误'
            })
        } else {
            res.json({
                code: 0,
                dat: item
            })
        }

    });

}

//
walleCateCtrl.remove = function (req, res, next) {

    var id = req.body.id;
    var condition ={
        $or: [
            { id: id },
            { parents: id }
        ]
    }

    // console.log('condition = ', condition);
    WalleCateModel.deleteMany(condition, function (err) {

        if (err) {

            console.log(err)

            res.status(500).json({
                code: -1,
                msg: '操作失败'
            })
        } else {
            res.json({
                code: 0,
               
            })
        }

    });

}

module.exports = walleCateCtrl;